package com.central.apps.controller;


import com.central.app.service.HandlerService;
import com.central.apps.common.util.DateUtiles;
import com.central.common.util.ToolUtil;
import io.swagger.models.auth.In;
import net.sf.json.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

@RestController
@RequestMapping("/personaldetails")
public class PersonaldetailsController {
    @Autowired
    private HandlerService handlerService;

    @PostMapping("/getinfo")
    public Object getinfo(@RequestBody Map<String, Object> params) {

        String appnum = MapUtils.getString(params, "appnum");
        //List<Map<String, String>> res = new ArrayList<>();
        List<Map<String, Object>> resList = new ArrayList<>();
        //Map<String, Map<String, Object>> mapres = new HashMap<>();
        //获取配置表数据，
        //strandfield:串联字段
        List<Map<String, Object>> list = handlerService.findBySql("select id ,tablename,querycondition,strandfield from gq_personaldetails where appnum = '" + appnum + "'");
        if (CollectionUtils.isNotEmpty(list)) {
            //String strandfieldvalue = MapUtils.getString(params, "strandfield");//串联字段值，如合同编号
            //String querycondition = MapUtils.getString(params, "querycondition");//主表查询条件
            for (Map<String, Object> stringObjectMap : list) {
                String where = (String) stringObjectMap.get("querycondition");
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if (where.contains(":" + entry.getKey())) {
                        where = where.replace(":" + entry.getKey(), "'" + entry.getValue().toString() + "'");
                    }

                }

                List<Map<String, Object>> listaccount = handlerService.findBySql("select * from " + stringObjectMap.get("tablename") + " t   where " + where);

                //List<Map<String, Object>> listaccount = handlerService.findBySql("select * from " + stringObjectMap.get("tablename") + "  where " + stringObjectMap.get("strandfield") + "='" + strandfieldvalue + "'");
//                String where = "";
//                for (Map<String, Object> objectMap : listaccount) {
//                    where =(String)stringObjectMap.get("querycondition");
//                    for (Map.Entry<String, Object> entry : objectMap.entrySet()) {
//                        if (where.contains(":" + entry.getKey())) {
//                            where = where.replace(":" + entry.getKey(), "'"+entry.getValue().toString()+"'");
//                        }
//                    }
//                }
                //id:主键
                //mid:主表主键
                //stationname:站台名字
                List<Map<String, Object>> list2 = handlerService.findBySql("select id,mid,stationname from gq_stationnode where mid = '" + stringObjectMap.get("id") + "'  order by stationcode asc");
                if (CollectionUtils.isNotEmpty(list2)) {
                    for (Map<String, Object> objectMap : list2) {
                        String stationname = MapUtils.getString(objectMap, "stationname");
                        //appnum :应用编号
                        //tablename:表名；
                        // timefield:时间统计字段；
                        // eventfield1：内容描述字段一（如：节点编号） eventfield2：内容描述字段2（如：节点名称）
                        List<Map<String, Object>> list3 = handlerService.findBySql("select isshowinfo,querycondition, appnum,description,tablename,timefield,eventfield1,eventfield2 from gq_applysinfo where mid = '" + objectMap.get("mid") + "' and sid = '" + objectMap.get("id") + "'");
                        if (CollectionUtils.isNotEmpty(list3)) {
                            //Map<Date, Object> dates = new HashMap<>();
                            List<Date> listTimes = new ArrayList<>();
                            List<Map<String, Object>> lists = new ArrayList<>();//存放多表
                            for (Map<String, Object> map : list3) {

                                Map<String, Object> tablemap = new HashMap<>();
                                Map<String, Object> tablemap1 = new HashMap<>();
                                String appnum1 = MapUtils.getString(map, "appnum"); //具体表应用编号
                                String tablename = MapUtils.getString(map, "tablename");
                                String timefield = MapUtils.getString(map, "timefield");
                                String eventfield1 = MapUtils.getString(map, "eventfield1");
                                String eventfield2 = MapUtils.getString(map, "eventfield2");
                                String description = MapUtils.getString(map, "description");//应用描述
                                String querycondition = MapUtils.getString(map, "querycondition");//子表查询条件
                                String isshowinfo = MapUtils.getString(map, "isshowinfo");//是否显示详细信息

                                //将配置的查询条件，把变量进行赋值替换
                                String where2 = "";
                                for (Map<String, Object> objectMap2 : listaccount) {
                                    where2 = querycondition;
                                    for (Map.Entry<String, Object> entry : objectMap2.entrySet()) {
                                        if (where2.contains(":" + entry.getKey())) {
                                            where2 = where2.replace(":" + entry.getKey(), "'" + entry.getValue().toString() + "'");
                                        }
                                    }
                                }
                                tablemap1.put("app", appnum1);
                                tablemap1.put("appName", description);
                                tablemap1.put("where", where2);
                                tablemap.put("appDesc", tablemap1);

                                StringBuffer sb = new StringBuffer();
                                sb.append("select id, ").append(timefield);
                                if (ToolUtil.isNotEmpty(eventfield1)) {
                                    sb.append(",").append(eventfield1);
                                }
                                if (ToolUtil.isNotEmpty(eventfield2)) {
                                    sb.append(",").append(eventfield2);
                                }
                                //sb.append("  from "+tablename+" where  "+MapUtils.getString(stringObjectMap,"strandfield")+"='"+strandfieldvalue+"'");
                                sb.append("  from " + tablename + " t where  " + where2);

                                System.out.println("sql==========" + sb.toString());
                                List<Map<String, Object>> list4 = handlerService.findBySql(sb.toString());
                                if (CollectionUtils.isNotEmpty(list4)) {
                                    List<Map<String, String>> childerList = new ArrayList<>();
                                    for (Map<String, Object> stringObjectMap1 : list4) {
                                        //表名 object 和biz_id
                                        //加一个过滤，审批通过完成的才能添加，查询流程表，是否审批完成
                                        int bizId = MapUtils.getInteger(stringObjectMap1, "id");
                                        List<Map<String, Object>> flowList = handlerService.findBySql("select status from biz_flow_app where object = '" + tablename + "' and biz_id =" + bizId);
                                        Date date = DateUtiles.parseStrToDate(MapUtils.getString(stringObjectMap1, timefield));
                                        String even1 = MapUtils.getString(stringObjectMap1, eventfield1);
                                        String even2 = MapUtils.getString(stringObjectMap1, eventfield2);
                                        if (CollectionUtils.isNotEmpty(flowList)) {
                                            if ("0".equals(MapUtils.getString(flowList.get(0), "status"))) {
                                                even2 = even2 + "（进行中）";
                                                //continue;
                                            } else {
                                                even2 = even2.replace("（进行中）", "")+"（已完成）";
                                            }
                                        } else {
                                            System.out.println();
                                            continue;
                                        }

                                        if (ToolUtil.isEmpty(eventfield1)) {
                                            //Date date = DateUtiles.parseStrToDate(MapUtils.getString(list4.get(0),timefield));
                                            //dates.put(date, description);
                                            tablemap1.put("children", "");
                                            listTimes.add(date);
                                            break;
                                        }


                                        Map<String, String> table2 = new HashMap<>();
                                        table2.put("name", even1 + ":" + even2);
                                        table2.put("app", appnum1);
                                        table2.put("id", bizId + "");
                                        childerList.add(table2);
                                        //dates.put(date, description + ":" + even1 + "," + even2);
                                        listTimes.add(date);
                                    }

                                    //是否显示详细数据
                                    if("是".equals(isshowinfo)){
                                        tablemap1.put("children", childerList);
                                    }else {
                                        tablemap1.put("children", "");
                                    }

                                    lists.add(tablemap);
                                }else {
                                    //数据为空也进行赋值
                                    lists.add(tablemap);
                                }

                            }
                            //整合成时间段，事件集合
                            //System.out.println(dates);
                            //if (listTimes != null && listTimes.size() > 0) {
                                //res.add(setMap(dates, stationname));
                                resList.add(setList(listTimes, stationname, lists));
                           // }

                        }


                    }
                }
            }
        }
        return resList;

    }

    public Map<String, Object> setList(List<Date> times, String title, Object content) {
        String start = null;
        String end = null;
        Map<String, Object> map = new HashMap<>();
        String timeres = "";
        if(times.size()>0){
           start = DateUtiles.getYmd(times.get(0));
           end  = DateUtiles.getYmd(times.get(times.size() - 1));
            if(start.equals(end)){
                timeres=start;
            }else {
                timeres = start + "到" + end;
            }
        }
        map.put("times", timeres);
        map.put("title", title);
        map.put("content", content);

        return map;
    }

    public Map<String, String> setMap(Map<Date, Object> dates, String title) {

        // Map<Date,Object> res = new HashMap<>();
        Set<Date> keySet = dates.keySet();
        Iterator<Date> iter = keySet.iterator();
        StringBuffer sb = new StringBuffer();
        List<Date> list = new ArrayList<>();
        while (iter.hasNext()) {
            Date key = iter.next();
            list.add(key);
            //res.put(key, dates.get(key));
            sb.append(",").append(dates.get(key));
        }
        String start = DateUtiles.getYmd(list.get(0));
        String end = DateUtiles.getYmd(list.get(list.size() - 1));
        String times = "";
        if(start.equals(end)){
            times=start;
        }else {
            times = start + "到" + end;
        }
        Map<String, String> map = new HashMap<>();
        map.put("times", times);
        map.put("title", title);
        map.put("content", sb.toString().replaceFirst(",", ""));
        return map;
    }

//    public static void main(String[] args) {
//        List<Map<String,Object>> lists = new ArrayList<>();
//        Map<String,Object>  map = new HashMap<>();
//        Map<String,Object> map1 = new HashMap<>();
//        map1.put("app","conApp");
//        map1.put("appName","合同收款");
//        map1.put("where","");
//        map.put("appDesc",map1);
//        List<Map<String,String>> list = new ArrayList<>();
//        Map<String,String> map2 = new HashMap<>();
//        map2.put("name","第一个收款节点");
//        map2.put("app","conApp");
//        map2.put("id","123");
//        Map<String,String> map3 = new HashMap<>();
//        map3.put("name","第二个收款节点");
//        map3.put("app","conApp");
//        map3.put("id","123");
//        list.add(map2);
//        list.add(map3);
//        map.put("children",list);
//
//        lists.add(map);
//        System.out.println(lists);
//    }
//    public static void main(String[] args) {
    //        List<Map<String,Object>> lists = new ArrayList<>();
//        Map<String,Object> res = new HashMap<>();
//        res.put("times","2023-01-01到2023-02-02");
//        res.put("title","合同签订");
//        res.put("content","合同申请，合同评审，合同签订");
//        lists.add(res);
//
//        Map<String,Object> res1 = new HashMap<>();
//        res1.put("times","2023-02-01到2023-03-02");
//        res1.put("title","节点完成情况");
//        res1.put("content","节点完成检查：0001，第一个节点 0002，第二个节点。收付款：0003，第三个节点");
//        lists.add(res1);
//        Map<String,Object> res2 = new HashMap<>();
//        res2.put("times","2023-03-01到2023-04-02");
//        res2.put("title","合同验收");
//        res2.put("content","合同验收");
//        lists.add(res2);
//        return lists;


//        //Map<String,Map<String,Object>> resmap = new HashMap<>();
//        Map<String,Object> resmap = new HashMap<>();
//        Map<String,Object> map = new HashMap<>();
//        List<String> list = new ArrayList<>();
//        list.add("合同申请");
//        list.add("合同评审");
//        list.add("合同签订");
//        map.put("合同签订",list);
//        resmap.put("2023-01-01到2023-02-02",map);
//        Map<String,Object> map1 = new HashMap<>();
//        List<String> list1 = new ArrayList<>();
//        list1.add("收付款，节点编号，节点名称");
//        list1.add("节点完成检查，节点编号，节点名称");
//        map1.put("节点完成情况",list1);
//        resmap.put("2023-01-01到2023-03-02",map1);
//        Map<String,Object> map2 = new HashMap<>();
//        List<String> list2 = new ArrayList<>();
//        list2.add("合同验收");
//        map2.put("合同验收",list2);
//        resmap.put("2023-01-01到2023-04-02",map2);
//        System.out.println(JSONObject.fromObject(resmap).toString());
//
//        List<Map<String,Object>> lists = new ArrayList<>();
//        Map<String,Object> res = new HashMap<>();
//        res.put("times","2023-01-01到2023-02-02");
//        res.put("title","合同签订");
//        res.put("content","合同申请，合同评审，合同签订");
//        lists.add(res);
//
//        Map<String,Object> res1 = new HashMap<>();
//        res1.put("times","2023-02-01到2023-03-02");
//        res1.put("title","节点完成情况");
//        res1.put("content","节点完成检查：0001，第一个节点 0002，第二个节点。收付款：0003，第三个节点");
//        lists.add(res1);
//        Map<String,Object> res2 = new HashMap<>();
//        res2.put("times","2023-03-01到2023-04-02");
//        res2.put("title","合同验收");
//        res2.put("content","合同验收");
//        lists.add(res2);
//        System.out.println(lists.toString());
//
//    }
}
